import { CustomLine } from '../../shape/line'
// 高亮
const magnetAvailabilityHighlighter = {
  name: 'stroke',
  args: {
    attrs: {
      fill: '#fff',
      stroke: '#47C769'
    }
  }
}

export default function () {
  const graph = this

  function update(view) {
    const cell = view.cell
    if (cell instanceof CustomLine) {
      cell.getPorts().forEach((port) => {
        const portNode = view.findPortElem(port.id, 'portBody')
        view.unhighlight(portNode, {
          highlighter: magnetAvailabilityHighlighter
        })
      })
      cell.updateOutPorts(graph)
    }
  }

  graph.on('edge:connected', (options) => {
    const { view } = options
    console.log(view)
    if (view.sourceView) {
      update(view.sourceView)
    }
    if (view.targetView) {
      update(view.targetView)
    }
  })

  graph.on('edge:removed', ({ edge, options }) => {
    if (!options.ui) {
      return
    }
    const targetId = edge.getTargetCellId()
    const target = graph.getCellById(targetId)
    const sourceId = edge.getSourceCellId()
    const source = graph.getCellById(sourceId)
    if (source instanceof CustomLine) {
      source.updateOutPorts(graph)
    }
    if (target instanceof CustomLine) {
      target.updateOutPorts(graph)
    }
  })

  return graph.createNode({
    shape: 'custom-line',
    ports: {
      items: [
        {
          group: 'outIn'
        },
        {
          group: 'right'
        },
        {
          group: 'left'
        }
      ]
    }
  })
}
